package jiaxa.com.jsbridge.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import jiaxa.com.jsbridge.AppApplication;
import jiaxa.com.jsbridge.Constant;
import jiaxa.com.jsbridge.R;
import jiaxa.com.jsbridge.amap.GaoDeMap;
import jiaxa.com.jsbridge.amap.AMapBean;
import jiaxa.com.jsbridge.bean.ApiBean;
import jiaxa.com.jsbridge.beanNative.NvDevice;
import jiaxa.com.jsbridge.beanNative.NvPhone;
import jiaxa.com.jsbridge.util.DeviceUtil;
import jiaxa.com.jsbridge.util.GsonUtil;
import jiaxa.com.jsbridge.util.ToastUtil;

@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {

    @ViewInject(R.id.bridgeView)
    private BridgeWebView bridgeView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide(); //隐藏标题栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);   //硬件加速
        x.view().inject(this);

        initWelcome();  //欢迎界面
        initWebView(); //初始化浏览器


        NvDevice entity=new NvDevice();
        entity.setPackageName(this.getPackageName());   //包名
        entity.setDeviceId(DeviceUtil.getDeviceId(AppApplication.getAppContext())); //设备号
        entity.setVersionCode(DeviceUtil.getVersionCode(AppApplication.getAppContext()));   //版本号
        entity.setVersionName(DeviceUtil.getVersionName(AppApplication.getAppContext()));   //版本名称
        entity.setAndroidLevel(DeviceUtil.getBuildLevel()); //android版本号
        entity.setAndroidVersion(DeviceUtil.getBuildVersion()); //android版本名称
        entity.setPhoneBrand(DeviceUtil.getPhoneBrand()); //手机品牌
        entity.setPhoneModel(DeviceUtil.getPhoneModel());   //手机型号
        Log.i("deviceid",GsonUtil.toJson(entity));

    }

    /**欢迎界面*/
    private void initWelcome() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(MainActivity.this, WelcomeActivity.class);
                startActivity(intent);
            }
        }).start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (bridgeView.canGoBack() && event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            bridgeView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initWebView() {
        /***打开本地缓存提供JS调用,至关重要**/
        WebSettings settings = bridgeView.getSettings();
        settings.setJavaScriptEnabled(true);//支持js
        settings.setDomStorageEnabled(true);//支持本地存储
        String cachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        settings.setAppCachePath(cachePath); //设置缓存路径
        settings.setAppCacheEnabled(true); //开启Application H5 Caches 功能
        settings.setDatabasePath(cachePath); //设置数据库缓存路径
        settings.setDatabaseEnabled(true);//开启 database storage API 功能
        settings.setAllowFileAccess(true); //启用或禁止WebView访问文件数据
        settings.setUseWideViewPort(true);//适应分辨率
        settings.setLoadWithOverviewMode(true);
        settings.setDefaultTextEncodingName("utf-8");//设置字符编码
        settings.setSupportZoom(false); // 支持缩放
        settings.setBuiltInZoomControls(false); // 启用内置缩放装置
        settings.setLoadsImagesAutomatically(true); // 支持自动加载图片

        bridgeView.setDefaultHandler(new DefaultHandler());
        bridgeView.setWebChromeClient(new WebChromeClient());
        bridgeView.setWebViewClient(new WebViewClient());   //设置具体WebViewClient
        bridgeView.setInitialScale(39);//适应全屏  39适应竖屏    57适应横屏
        String url = "http://cangdu.org:8001/msite?geohash=39.97705,116.406118";//"http://192.168.18.125:9901";//"http://m.baidu.com/";   //
        bridgeView.loadUrl(url);
        bridgeView.registerHandler("jsCallNative", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i(Constant.TAG.jsCall, data);
                jsCallNative(data, function);
            }
        });
    }

    /**
     * 初始化，原生调用H5
     */
    private void nativeCallJs(String data) {
        Log.i(Constant.TAG.nativeCall, data);
        bridgeView.callHandler("nativeCallJs", data, new CallBackFunction() {
            @Override
            public void onCallBack(String data) {
                Log.i(Constant.TAG.nativeCall, data);
            }
        });
    }

    /**
     * 初始化，原生调用H5
     */
    private void nativeCallJs(String data, CallBackFunction function) {
        bridgeView.callHandler("nativeCallJs", data, function);
    }


    /**
     * 初始化，H5调用原生
     */
    private void jsCallNative(String data, CallBackFunction function) {
        ApiBean json = new Gson().fromJson(data, ApiBean.class);
        if (json == null || json.getCode() == null) {
            return;
        }
        String apiCode = json.getCode();
        switch (apiCode) {
            case Constant.CALLMODE.api:
                callJava(json, function);
                break;
            case Constant.CALLMODE.location:
                callLocation(json, function);
                break;
            case Constant.CALLMODE.device:
                callDevice(json, function);
                break;
            case Constant.CALLMODE.phone:
                callPhone(json);
                break;
            case Constant.CALLMODE.scan:
                callScan(json, function);
                break;
            case Constant.CALLMODE.url:
                callURL(json);
                break;
            case Constant.CALLMODE.pdf:
                callPDF(json);
                break;
        }
    }

    private void callJava(final ApiBean json, final CallBackFunction function) {
        RequestParams params=new RequestParams("");
        params.setAsJsonContent(true);
        params.setBodyContent(GsonUtil.toJson(json.getReqData()));
        x.http().post(null, new Callback.CommonCallback<Object>() {
            @Override
            public void onSuccess(Object result) {
                String res = result.toString();
                json.setResData(res);
                function.onCallBack(GsonUtil.toJson(json));
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                json.setErrorMsg(ex.getMessage());
                function.onCallBack(GsonUtil.toJson(json));
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    /**
     * 定位信息（返回）
     */
    private void callLocation(final ApiBean apiBean, final CallBackFunction function) {
        final AMapLocationClient mapClient = GaoDeMap.initLocation(AppApplication.getAppContext(), new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        AMapBean amapBean = new AMapBean(aMapLocation);
                        apiBean.setReqData(amapBean);
                        Log.i(Constant.TAG.map, new Gson().toJson(apiBean));
                        function.onCallBack(new Gson().toJson(apiBean));
                    }
                }
            }
        });
        mapClient.startLocation();
    }

    /**
     * 拨打电话
     */
    private void callPhone(final ApiBean apiBean) {
        NvPhone phone = GsonUtil.toObject(apiBean.getReqData().toString(), NvPhone.class);
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone.getPhone()));
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ToastUtil.show("请开启电话权限");
            return;
        }
        AppApplication.getAppContext().startActivity(intent);
        nativeCallJs("");
    }

    /**
     * 打开第三方URL
     */
    private void callURL(final ApiBean apiBean) {
        Intent intent = new Intent(MainActivity.this, UrlActivity.class);
        intent.putExtra(Constant.CALLMODE.url, apiBean.getReqData().toString());
        MainActivity.this.startActivity(intent);
    }

    /**
     * 打开PDF文件
     */
    private void callPDF(final ApiBean apiBean) {
        Intent intent = new Intent(MainActivity.this, PdfActivity.class);
        intent.putExtra(Constant.CALLMODE.pdf, apiBean.getReqData().toString());
        MainActivity.this.startActivity(intent);
    }

    /**
     * 获取手机信息*/
    private void callDevice(final ApiBean apiBean, final CallBackFunction function){
        NvDevice entity=new NvDevice();
        entity.setPackageName(this.getPackageName());   //包名
        entity.setDeviceId(DeviceUtil.getDeviceId(AppApplication.getAppContext())); //设备号
        entity.setVersionCode(DeviceUtil.getVersionCode(AppApplication.getAppContext()));   //版本号
        entity.setVersionName(DeviceUtil.getVersionName(AppApplication.getAppContext()));   //版本名称
        entity.setAndroidLevel(DeviceUtil.getBuildLevel()); //android版本号
        entity.setAndroidVersion(DeviceUtil.getBuildVersion()); //android版本名称
        entity.setPhoneBrand(DeviceUtil.getPhoneBrand()); //手机品牌
        entity.setPhoneModel(DeviceUtil.getPhoneModel()); //手机型号

        apiBean.setResData(entity);
        function.onCallBack(GsonUtil.toJson(apiBean));
    }

    /**
     * 获取二维码信息*/
    private void callScan(final ApiBean apiBean, final CallBackFunction function){
        NvDevice entity=new NvDevice();
        
        apiBean.setResData(entity);
        function.onCallBack(GsonUtil.toJson(apiBean));
    }
}
